//
//  XmppClient.m
//  MoCard
//
//  Created by 水石 温 on 11-9-16.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "NetEventHandler.h"
#import "DDXML.h"

//#import "NSStringCatalog.h"
#import <SystemConfiguration/SystemConfiguration.h>
//#import "NSDataCatalog.h"

//#import "LvAlertView.h"
//#import "NSFileManagerCatalog.h"
//#import "UIApplicationCategory.h"
//#import "Prefs.h"
//#import "LocationHelper.h"
#import <netinet/in.h>

SCNetworkReachabilityRef reachability;

@implementation NetEventHandler
//@synthesize socket,xmlParser;

#pragma -
#pragma ---

-(id)init {
    self = [super init];
    socket=[[AsyncSocket alloc] initWithDelegate:self];
    [self performSelector:@selector(setupNetworkMonitoring)];
    xmlParser=nil;

    return self;
}



#pragma -
#pragma client request method

-(void)connectToHost:(NSString*)ip onPort:(NSInteger)aPort {
    NSError *error = nil;
//    NSLog(@"connect to host  ip:%@ port:%d", ip, aPort);
    [socket connectToHost:ip onPort:aPort withTimeout:30 error:&error];
}

-(void)sendString:(NSString*)str {
    NSLog(@"SEND: %@", str);
    [socket writeData:[str dataUsingEncoding:NSUTF8StringEncoding] withTimeout:30 tag:0];
}

-(void)sendElement:(DDXMLElement*)xmlElement {
    NSString *xmlStr = [xmlElement compactXMLString];
    [self sendString:xmlStr];
}

-(BOOL)isConnected {
    return [socket isConnected];
}

-(void)disconnect {
    [socket disconnect];
}


#pragma -
#pragma asyncsocket delegate methods

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err {
    NSLog(@"willDisconnectWithError:%@",[err localizedDescription]);
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock {
    NSLog(@"onSocketDidDisconnect");
    if (xmlParser) {
        [xmlParser release];
        xmlParser = nil;
    }
//    [curXmppClient performSelector:@selector(didDisconnect)];
}

- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket {
    NSLog(@"didAcceptNewSocket");
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
    [socket readDataWithTimeout:-1 tag:0];
    if (xmlParser) {
        [xmlParser release];
        xmlParser = nil;
    }
    xmlParser = [[XMPPParser alloc] initWithDelegate:self];
//    [curXmppClient performSelector:@selector(didConnect)];
    NSLog(@"didConnectToHost");
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    [sock readDataWithTimeout:-1 tag:0];
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"RECV:%@", str);
    [str release];
    [xmlParser parseData:data];//收到数据，调用xml解析器
}


- (void)onSocket:(AsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag {
    NSLog(@"didReadPartialDataOfLength:%d",partialLength);
}


#pragma -
#pragma xml parse callback
//- (void)xmppParser:(XMPPParser *)sender didReadRoot:(DDXMLElement *)root {
//    NSLog(@"didReadRoot:%@",[root name]);
//    
////    [curXmppClient  performSelector:@selector(streamDidOpen:) withObject:root  ] ;
//}
//
//- (void)xmppParser:(XMPPParser *)sender didReadElement:(DDXMLElement *)element {
////    [curXmppClient performSelector:@selector(didReadElement:) withObject:element];
//}

- (void)xmppParserDidEnd:(XMPPParser *)sender {
    NSLog(@"xmppParserDidEnd");
    [socket disconnect];
}

- (void)xmppParser:(XMPPParser *)sender didFail:(NSError *)error {
    NSLog(@"didFail %@",error);
    [socket disconnect];
}

#pragma -
#pragma other

-(NSString*)currentNetworkType {
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
	
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    NSString *networkType = @"iOS-WIFI";
    if (flags & kSCNetworkReachabilityFlagsIsWWAN) {
        // 3G/Edge/GPRS
        networkType = @"iOS-GPRS";
        NSLog(@"Net changed to GPRS");
    }
    return networkType;
}

#pragma -
#pragma network status management
static void ReachabilityChanged(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info) {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSLog(@"网络状态改变:%@,%d,%@",target, flags, info);
//    [[XmppClient share] performSelector:@selector(networkStateChanged) withObject:nil];
	[pool release];
}



-(void)setupNetworkMonitoring {
	reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [@"117.135.132.61" UTF8String]);
    if (reachability) {
        SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
        SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
        SCNetworkReachabilitySetCallback(reachability, ReachabilityChanged, &context);
    }
}

-(void)teardownNetworkMonitoring {
	if (reachability) {
		SCNetworkReachabilityUnscheduleFromRunLoop(reachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
		CFRelease(reachability);
		reachability = NULL;
	}
}


-(void)dealloc {
    [socket disconnect];
    [self performSelector:@selector(teardownNetworkMonitoring)];
    [socket release];
    [xmlParser release];
    [super dealloc];
}



@end
